<?php
/*
 * @美潮风
 * @功能说明：用户中心
 * @更新说明：暂无更新
 * @文件名 UserController.class.php
 * @编码 UTF-8
 * @创建时间 2015-7-21 下午3:38:52
 * @创建人 XING
 */

namespace home\Controller;
use Think\Controller;

class TakeController extends ApibaseController {

    /*
     * 药品领用管理
     * @date: 2017-11-15下午5:06:13
     * @editor: zyy
     */
    public function drug_index(){
        /*参数初始化*/
        $page    = I('get.page', 1);
        $perpage = 10;
        $url     = [];
        $list    = M('Drugtake');
        if (I('get.take_depart')) {
            $list           = $list->where(['take_depart' => I('get.take_depart')]);
            $url['take_depart'] = I('get.take_depart');
        }
        if (I('get.use_class')) {
            $list           = $list->where(['use_class' => I('get.use_class')]);
            $url['use_class'] = I('get.use_class');
        }
        if (I('get.group_place')) {
            $list             = $list->where(['group_place' => I('get.group_place')]);
            $url['group_place'] = I('get.group_place');
        }
        if (I('get.order_id')) {
            $list           = $list->where(['order_id' => I('get.order_id')]);
            $url['order_id'] = I('get.order_id');
        }
        $stime = I('get.start_date');
        $etime = I('get.end_date');
        if ($stime && !$etime) {
            $list   = $list->where(['group_date' => ['egt', $stime]]);
            $url['stime'] = $stime;
        } elseif (!$stime && $etime) {
            $list   = $list->where(['group_date' => ['elt', $etime]]);
            $url['etime'] = $etime;
        } elseif ($stime && $etime) {
            $list   = $list->where(['group_date' => ['between', [$stime, $etime]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
        $copyObject = clone $list;
        $drugIndex    = $list->where(['take_type'=>1])->order('add_at desc')
            ->page($page, $perpage)
            ->select();
        $this->assign('getData',$drugIndex);
        $this->assign('page', setPage($copyObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->display('take/drug_index');
    }

    /*
     * 添加领用组会信息
     * @date: 2017-11-15下午5:06:13
     * @editor: zyy
     */
    public function takegroup_add(){
        if(I('post.dosubmit')){
            if (!I('post.take_depart') || !I('post.use_class')){
                $this->showtips('领用课别和领料部门为必填项');
            }
            if(I('post.id')){
                $effectId = M('Drugtake')->where(array('id'=>I('post.id')))
                    ->setField(array(
                        'use_class' => I('post.use_class'),
                        'group_place' => I('post.group_place'),
                        'group_doctor' => I('post.group_doctor'),
                        'group_date' => I('post.group_date'),
                        'apply_user' => I('post.apply_user'),
                        'depart_leader' => I('post.depart_leader'),
                        'take_depart' => I('post.take_depart'),
                        'take_user' => I('post.take_user'),
                        'stock_leader' => I('post.stock_leader'),
                        'send_user' => I('post.send_user'),
                        'dealreturn_user' => I('post.dealreturn_user'),
                        'remark' => I('post.remark'),
                        'operator' => getLoginUname(),
                        'update_at' => time()
                    ));

                if($effectId){
                    $this->showtips('药品领用更新成功');
                }else{
                    $this->showtips('操作失败');
                }
            }

            $orderid = date("Ymd").rand(10000,99999);
            $data = array(
                'order_id' => $orderid,
                'use_class' => I('post.use_class'),
                'group_place' => I('post.group_place'),
                'group_doctor' => I('post.group_doctor'),
                'group_date' => I('post.group_date'),
                'apply_user' => I('post.apply_user'),
                'depart_leader' => I('post.depart_leader'),
                'take_user' => I('post.take_user'),
                'take_depart' => I('post.take_depart'),
                'stock_leader' => I('post.stock_leader'),
                'send_user' => I('post.send_user'),
                'dealreturn_user' => I('post.dealreturn_user'),
                'remark' => I('post.remark'),
                'operator' => getLoginUname(),
                'add_at' => time(),
                'update_at' => time()
            );
            $add_id = M('Drugtake')->add($data);
            if($add_id){
                $this->showtips('药品领用组会添加成功','/take/takegroup_add/id/'.$add_id.'/orderid/'.$orderid.'?res=2-1');
            }else{
                $this->showtips('操作失败');
            }
        }
        if(I('get.id')){
            //组会领用信息
            $takeData = M('Drugtake')->where(array('id'=>I('get.id')))->find();
            //组会的药品列表
            $drugList = M('Usedetail')->where(['take_orderid'=>I('get.orderid'),'take_type'=>'药品','delete_at'=>0])->select();
            if($drugList){
                foreach ($drugList as $k=>$val){
                    $drugList[$k]['drugMsg'] = M('Druglist')->where(['id'=>$val['drug_id']])->find();
                }
            }
            //组会的转出药品列表
            $outList = M('OutinDetail')->where(['take_orderid'=>I('get.orderid'),'delete_at'=>0])->select();
            if($outList){
                foreach ($outList as $k=>$val){
                    $useDetail = M('Usedetail')->where(['id'=>$val['takedrug_id']])->find();
                    $outList[$k]['outDrugMsg'] = M('Druglist')->where(['id'=>$useDetail['drug_id']])->find();
                    $outList[$k]['takeMsg'] = M('Drugtake')->where(['order_id'=>$val['income_orderid']])->find();
                }
            }

            //组会的转入药品列表
            $inList = M('OutinDetail')->where(['income_orderid'=>I('get.orderid'),'delete_at'=>0])->select();
            if($inList){
                foreach ($inList as $k=>$val){
                    $useDetail = M('Usedetail')->where(['id'=>$val['takedrug_id']])->find();
                    $inList[$k]['inDrugMsg'] = M('Druglist')->where(['id'=>$useDetail['drug_id']])->find();
                    $inList[$k]['takeMsg'] = M('Drugtake')->where(['order_id'=>$val['take_orderid']])->find();
                }
            }

            //组会的还货入库明细
            $return_storage = M('ReturnStock')->where(['take_orderid'=>I('get.orderid')])->select();
            if($return_storage){
                foreach ($return_storage as $k=>$val){
                    $return_storage[$k]['return_drugMsg'] = M('Druglist')->where(['id'=>$val['drug_id']])->find();
                }
            }

            $this->assign('drugList',$drugList);
            $this->assign('outList',$outList);
            $this->assign('inList',$inList);
            $this->assign('return_storage',$return_storage);
            $this->assign('takeData',$takeData);
        }


        $this->display('take/takegroup_add');
    }

    /*
     * 添加领用组会的药品信息
     * @date: 2017-11-16上午11:06:13
     * @editor: zyy
     */
    public function take_drug(){
        if(I('post.submit')){
            if(I('post.id')){
                //之前领出量为零，后面更新领出量的情况
                $takeOne = M('Usedetail')->where(array('id'=>I('post.id')))->find();
                if($takeOne['take_num'] == 0 && I('post.take_num') > 0){
                    $stockModel = M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'药品']);
                    $stock = $stockModel->find();
                    if($stock['stock_num'] < I('post.take_num')){
                        $this->showtips('领用的药品库存不足');
                    }
                    M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'药品'])->setDec('stock_num',I('post.take_num'));
                }
                $effectId = M('Usedetail')->where(array('id'=>I('post.id')))
                    ->setField(array(
                        'apply_num' => I('post.apply_num'),
                        'take_num' => I('post.take_num'),
                        'take_type' => '药品',
                        'realuse_num' => I('post.realuse_num'),
                        'last_num' => I('post.last_num'),
                        'waste_num' => I('post.waste_num'),
                        'cwwuse_num' => I('post.cwwuse_num'),
                        'remark' => I('post.remark'),
                        'update_at' => time()
                    ));
                if($effectId){
                    $this->showtips('领用药品信息更新成功');
                }else{
                    $this->showtips('操作失败');
                }
            }
            //药品领用数量不能大于对应仓库药品的库存数量
            $sel_stock = M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'药品'])->find();
            if(I('post.take_num') > $sel_stock['stock_num']){
                $this->showtips('药品领用数量不能大于对应仓库药品的库存数量');
            }
            //库存表对应仓库药品的库存数量-领出量
            if(I('post.take_num') > 0){
                $stockModel = M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'药品']);
                $stock = $stockModel->find();
                if($stock['stock_num'] < I('post.take_num')){
                    $this->showtips('领用的药品库存不足');
                }
                M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'药品'])->setDec('stock_num',I('post.take_num'));
            }

            if(I('post.own_house') && I('post.drug_id')){
                $take_orderid = M('Drugtake')->where(['id'=>I('post.take_id')])->getField('order_id');
                $data = array(
                    'take_id' => I('post.take_id'),
                    'take_orderid' => $take_orderid,
                    'drug_id' => I('post.drug_id'),
                    'apply_num' => I('post.apply_num'),
                    'take_num' => I('post.take_num'),
                    'take_type' => '药品',
                    'realuse_num' => I('post.realuse_num'),
                    'last_num' => I('post.last_num'),
                    'waste_num' => I('post.waste_num'),
                    'cwwuse_num' => I('post.cwwuse_num'),
                    'remark' => I('post.remark'),
                    'warehouse' => I('post.own_house'),
                    'add_at' => time(),
                    'update_at' => time()
                );
                if(M('Usedetail')->add($data)){
                    $this->showtips('领用药品信息添加成功');
                }else{
                    $this->showtips('操作失败');
                }
            }else{
                $this->showtips('参数缺失');
            }

        }
        if(I('get.id')){
            $takeData = M('Usedetail')->where(array('id'=>I('get.id')))->find();
            $drugMsg = M('Druglist')->where(['id'=>$takeData['drug_id']])->find();
            $this->assign('drugList',$takeData);
            $this->assign('drugMsg',$drugMsg);
        }
        $takeData = M('Drugtake')->where(array('id'=>I('get.take_id')))->find();
        $take_depart = $takeData['take_depart'] == 1 ? '技术部' : ($takeData['take_depart'] == 2 ? '仪器部（6980）' : '');
        //仓库
        $warehouse = M('Warehouse')->select();
        $this->assign('warehouse',$warehouse);
        $this->assign('take_depart',$take_depart);
        $this->display('take/take_drug');
    }

    /*
     * 添加领用组会的耗材信息
     * @date: 2017-11-22上午11:46:13
     * @editor: zyy
     */
    public function take_material(){
        if(I('post.submit')){
            //耗材领用数量不能大于对应仓库药品的库存数量
            if(!I('post.id')) {
                $sel_stock = M('Stock')->where(['drug_id' => I('post.drug_id'), 'warehouse' => I('post.own_house') , 'type'=>'耗材'])->find();
                if (I('post.take_num') > $sel_stock['stock_num']) {
                    $this->showtips('耗材领用数量不能大于对应仓库耗材的库存数量');
                }
            }
            $take_orderid = I('post.order_id');
            if(I('post.id')){
                $takeOne = M('Usedetail')->where(array('id'=>I('post.id')))->find();

                //之前领出量为零，后面更新领出量的情况
                 if($takeOne['take_num'] == 0 && I('post.take_num') > 0){
                     $stockModel = M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'耗材']);
                     $stock = $stockModel->find();
                     if($stock['stock_num'] < I('post.take_num')){
                         $this->showtips('领用的耗材库存不足');
                     }
                     M('Stock')->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.own_house'),'type'=>'耗材'])->setDec('stock_num',I('post.take_num'));
                 }
                    $effectId = M('Usedetail')->where(array('id'=>I('post.id')))
                        ->setField(array(
                            'apply_num' => I('post.apply_num'),
                            'take_num' => I('post.take_num'),
                            'remark' => I('post.remark'),
                            'update_at' => time()
                        ));
                 if($effectId){
                    $this->showtips('领用耗材信息更新成功');
                }else{
                    $this->showtips('操作失败');
                }
            }

            if(I('post.own_house') && I('post.drug_id')) {
                $data = array(
                    'take_id' => I('post.take_id'),
                    'take_orderid' => $take_orderid,
                    'drug_id' => I('post.drug_id'),
                    'apply_num' => I('post.apply_num'),
                    'take_num' => I('post.take_num'),
                    'take_type' => '耗材',
                    'remark' => I('post.remark'),
                    'warehouse' => I('post.own_house'),
                    'add_at' => time(),
                    'update_at' => time()
                );
                //库存表对应仓库药品的库存数量-领出量
                if (I('post.take_num') > 0) {
                    $stockModel = M('Stock')->where(['drug_id' => I('post.drug_id'), 'warehouse' => I('post.own_house'), 'type' => '耗材']);
                    $stock = $stockModel->find();
                    if ($stock['stock_num'] < I('post.take_num')) {
                        $this->showtips('领用的耗材库存不足');
                    }
                    M('Stock')->where(['drug_id' => I('post.drug_id'), 'warehouse' => I('post.own_house'), 'type' => '耗材'])->setDec('stock_num', I('post.take_num'));
                }
                if (M('Usedetail')->add($data)) {
                    $this->showtips('领用耗材信息添加成功');
                } else {
                    $this->showtips('操作失败');
                }
            }else{
                $this->showtips('参数缺失');
            }
        }
        if(I('get.id')){
            $takeData = M('Usedetail')->where(array('id'=>I('get.id')))->find();
            $drugMsg = M('Druglist')->where(['id'=>$takeData['drug_id']])->find();
            $this->assign('drugList',$takeData);
            $this->assign('drugMsg',$drugMsg);
        }
        //仓库
        $warehouse = M('Warehouse')->select();
        $this->assign('warehouse',$warehouse);
        $this->display('take/take_material');
    }

    /*
     * 转出领用组会的药品信息
     * @date: 2017-11-17下午15:06:13
     * @editor: zyy
     */
    public function out_take_drug(){
        if(I('post.submit')){
            //转出数量不能大于剩余数量
            $takeDrug = M('Usedetail')->where(['id'=>I('post.takedrug_id')])->find();
            if($takeDrug['last_num'] < I('post.out_num')){
                $this->showtips('转出数量不能大于剩余数量');
            }
            if(!I('post.income_orderid')){
                $this->showtips('必须有领用单号才能转出！');
            }
            $exist = M('Drugtake')->where(['order_id' => trim(I('post.income_orderid'))])->find();
            if(!$exist){
                $this->showtips('领用单号有误！');
            }

            $OutinDetail = M('OutinDetail');
            $Usedetail   = M('Usedetail');
            $OutinDetail->startTrans();
            $Usedetail->startTrans();
            $data = array(
                'income_orderid' => I('post.income_orderid'),
                'take_orderid'   => I('post.take_orderid'),
                'takedrug_id'    => I('post.takedrug_id'),
                'out_num'        => I('post.out_num'),
                'get_nurse'      => I('post.get_nurse'),
                'remark'         => I('post.remark'),
                'warehouse'      => $takeDrug['warehouse'],
                'operator'       => getLoginUname(),
                'add_at'         => time(),
                'update_at'      => time()
            );
            $rs = $OutinDetail->lock(true)->add($data);
            if($rs){
                //领用组会对应仓库的药品剩余量-转出量
                $out = $Usedetail->lock(true)->where(['id'=>$takeDrug['id']])->setDec('last_num',I('post.out_num'));
                //别人转过来的再转出
                $detail_one = $Usedetail->where(['id'=>$takeDrug['id']])->find();
                $Usedetail->lock(true)->where(['id'=>$takeDrug['id'],'apply_num'=>0])->setField(['remark'=>$detail_one['remark'].'//领用单号'.I('post.take_orderid').'在'.date('Y-m-d H:i:s').'转出数量'.I('post.out_num'),'is_outin'=>1]);

                //接收方有对应仓库药品则剩余量+转出量  没有则新增
                $is_havedrug = M('Usedetail')->where(['take_orderid'=>I('post.income_orderid'),'drug_id'=>$takeDrug['drug_id'],'warehouse'=>$takeDrug['warehouse']])->find();
                if($is_havedrug){
                    $in = $Usedetail->lock(true)->where(['id'=>$is_havedrug['id']])->setInc('last_num',I('post.out_num'));
                }else{
                    $in = $Usedetail->lock(true)->add([
                        'take_orderid'=>I('post.income_orderid'),
                        'drug_id'=>$takeDrug['drug_id'],
                        'warehouse'=>$takeDrug['warehouse'],
                        'take_num'=>I('post.out_num'),
                        'take_type'=>'药品',
                        'last_num'=>I('post.out_num'),
                        'remark'=>'领用单号'.I('post.take_orderid').'在'.date('Y-m-d H:i:s').'转入数量'.I('post.out_num'),
                        'is_outin'=>1,
                        'operator'=> getLoginUname(),
                        'add_at'=>time(),
                        'update_at'=>time(),
                    ]);
                }
                if($out && $in){
                    $OutinDetail->commit();
                    $Usedetail->commit();
                    $this->showtips('药品转出成功');
                }else{
                    $OutinDetail->rollback();
                    $Usedetail->rollback();
                    $this->showtips('药品转出失败');
                }

            }else{
                $OutinDetail->rollback();
                $this->showtips('操作失败');
            }
        }
        $own_order = M('Drugtake')->where(['order_id'=>I('get.order_id')])->find();
        //符合条件的领用单号（转入单号）#组会日期大于当前时间的 #排除自己的单号
        $where = ['take_type'=>'1'];
        if(I('get.order_id')){
            $where['order_id'] = ['neq',I('get.order_id')];
        }
        $where['group_date'] = ['egt',$own_order['group_date']];
        $groupDate = M('Drugtake')->where($where)->getField('order_id',true);
        $this->assign('groupDate',$groupDate);
        $this->assign('order_id',I('get.order_id'));
        $this->display('take/out_take_drug');
    }

    /**
     * 下拉框变成选择之后 获取信息列表
     * 2018-1-23
     * User: liuqi
     */
    public function  getGroupList(){
        $own_order = M('Drugtake')->where(['order_id'=>I('post.order_id')])->find();
        if(I('post.order_id')){
            $where['order_id'] = ['neq',I('post.order_id')];
        }
        $where['group_date'] = ['egt',$own_order['group_date']];
        $groupDate = M('Drugtake')->where($where)->getField('order_id',true);
        $new_arr = [];
        foreach($groupDate as $k=>$v){
            $new_arr[$k]['id'] = $v;
            $new_arr[$k]['text'] = $v;
        }

        dataFormat($new_arr,0,'suc');

    }



    //返回指定仓库的药品信息
    public function onehouse_drug(){
        //入库药品列表(返回数组编号和药品名)
        if(I('post.sel_house')){
            $Instock = M('Instock');
            $type = I('post.type');
            if($type){
                $Instock = $Instock->where(['type'=>$type]);
            }
            $stock_drug = $Instock->where(['warehouse'=>I('post.sel_house'),'delete_at'=>0])->getField('drug_id,drug_name');
            dataFormat($stock_drug, '0', 'success');
        }else{
            dataFormat('', 1, '参数有误');
        }
    }

    /*
     * 删除领用组会的药品信息
     * @date: 2017-11-16下午17:06:13
     * @editor: zyy
     */
    public function del_takedrug(){
        if(I('post.ids')){
            $ids = substr(I('post.ids'),0,-1);
            $useDetail = M('Usedetail');
            $stock = M('Stock');
            $useDetail->startTrans();
            $stock->startTrans();
            //判断已经使用过的药品不能删除
                $ids_arr = explode(',',$ids);
                if($ids_arr){ foreach ($ids_arr as $v){
                    $data = M('Usedetail')->where(['id'=>$v])->find();
                    $is_return = M('ReturnStock')->where(['usedetail_id'=>$v])->find();
//                    if($data['realuse_num']){
//                        echo json_encode(['code'=>'0','msg'=>'已经使用过的不能删除']);exit;
//                    }
                    if($is_return){
                        echo json_encode(['code'=>'0','msg'=>'还货入库的药品不能删除']);exit;
                    }
                    if($data['is_outin']){
                        echo json_encode(['code'=>'0','msg'=>'转入转出的药品不能删除']);exit;
                    }
                    //已经删除的需要库存回归
                    $num_back = $stock->lock(true)->where(['drug_id'=>$data['drug_id'],'warehouse'=>$data['warehouse']])->setInc('stock_num',$data['take_num']);
                }}

            $useDetail->lock(true)->where('id in ('.$ids.')')->setField(['delete_at'=>time()]);
            if($num_back){
                $stock->commit();
                $useDetail->commit();
                echo json_encode(['code'=>'1','msg'=>'删除成功']);exit;
            }else{
                $stock->rollback();
                $useDetail->rollback();
                echo json_encode(['code'=>0,'msg'=>'删除失败']);exit;
            }
        }
    }

    /*
     * 删除领用组会的药品信息
     * @date: 2017-11-16下午17:06:13
     * @editor: zyy
     */
    public function del_takeMaterial(){
        if(I('post.ids')){
            $ids = substr(I('post.ids'),0,-1);
            $useDetail = M('Usedetail');
            $stock = M('Stock');
            $useDetail->startTrans();
            $stock->startTrans();
            $ids_arr = explode(',',$ids);
            if($ids_arr){ foreach ($ids_arr as $v){
                $data = M('Usedetail')->where(['id'=>$v])->find();
                //已经删除的需要库存回归
                $stock->lock(true)->where(['drug_id'=>$data['drug_id'],'warehouse'=>$data['warehouse']])->setInc('stock_num',$data['take_num']);
            }}
            $rs = $useDetail->lock(true)->where('id in ('.$ids.')')->setField(['delete_at'=>time()]);
            if($rs){
                $stock->commit();
                $useDetail->commit();
                echo json_encode(['code'=>'1','msg'=>'删除成功']);exit;
            }else{
                $stock->rollback();
                $useDetail->rollback();
                echo json_encode(['code'=>0,'msg'=>'删除失败']);exit;
            }
        }
    }

    /*
     * 删除转出领用组会的药品信息
     * @date: 2017-11-16下午17:06:13
     * @editor: zyy
     */
    public function del_takedrug_out(){
        if(I('post.ids_out')){
            $ids = substr(I('post.ids_out'),0,-1);
            $useDetail = M('Usedetail');
            $outInModel = M('OutinDetail');
            $useDetail->startTrans();
            $outInModel->startTrans();
            $ids_arr = explode(',',$ids);
            if($ids_arr){ foreach ($ids_arr as $v){
                $data = M('OutinDetail')->where(['id'=>$v])->find();
                $detail = M('Usedetail')->where(['id'=>$data['takedrug_id']])->find();
                //查看转入的剩余量是否足够
                $inDetail = M('Usedetail')->where(['take_orderid'=>$data['income_orderid'],'warehouse'=>$data['warehouse'],'drug_id'=>$detail['drug_id']])->find();
                if($inDetail['last_num'] < $data['out_num']){
                    echo json_encode(['code'=>0,'msg'=>'接收组会的剩余量不足，转出数据删除失败']);exit;
                }
                $dec =$useDetail->lock(true)->where(['take_orderid'=>$data['income_orderid'],'warehouse'=>$data['warehouse'],'drug_id'=>$detail['drug_id']])->setDec('last_num',$data['out_num']);
                //已经删除的需要剩余量回归
                $inc =$useDetail->lock(true)->where(['id'=>$data['takedrug_id']])->setInc('last_num',$data['out_num']);
            }}
            if($dec && $inc){
                $rs = $outInModel->lock(true)->where('id in ('.$ids.')')->setField(['delete_at'=>time()]);
                if($rs){
                    $useDetail->commit();
                    $outInModel->commit();
                    echo json_encode(['code'=>'1','msg'=>'删除成功']);exit;
                }else{
                    $useDetail->rollback();
                    $outInModel->rollback();
                    echo json_encode(['code'=>'0','msg'=>'删除失败']);exit;
                }
            }else{
                $useDetail->rollback();
                echo json_encode(['code'=>'0','msg'=>'删除失败']);exit;
            }
        }
    }

    /**
     * 入库的时候 选择药品获取对应信息
     */
    public function getTakeInfo()
    {
        if (I('post.orderid')) {
            $data = M('Drugtake')->where(['order_id' => trim(I('post.orderid'))])->find();
            dataFormat($data, '0', 'success');
        } else {
            dataFormat('', 1, '参数有误');
        }
    }

    /*
     * 耗材领用管理
     * @date: 2017-11-21下午5:06:13
     * @editor: zyy
     */
    public function material_index(){
        /*参数初始化*/
        $page    = I('get.page', 1);
        $perpage = 10;
        $url     = [];
        $list    = M('MaterialTake');
        if (I('get.take_place')) {
            $list             = $list->where(['take_place' => I('get.take_place')]);
            $url['take_place'] = I('get.take_place');
        }
        if (I('get.order_id')) {
            $list           = $list->where(['order_id' => I('get.order_id')]);
            $url['order_id'] = I('get.order_id');
        }
        $stime = I('get.start_date');
        $etime = I('get.end_date');
        if ($stime && !$etime) {
            $list   = $list->where(['take_date' => ['gt', $stime]]);
            $url['stime'] = $stime;
        } elseif (!$stime && $etime) {
            $list   = $list->where(['take_date' => ['lt', $etime]]);
            $url['etime'] = $etime;
        } elseif ($stime && $etime) {
            $list   = $list->where(['take_date' => ['between', [$stime, $etime]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
        $copyObject = clone $list;
        $drugIndex    = $list->order('add_at desc')
            ->page($page, $perpage)
            ->select();
        $this->assign('getData',$drugIndex);
        $this->assign('page', setPage($copyObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->display('take/material_index');
    }

    /*
     * 添加耗材领用信息
     * @date: 2017-11-21下午5:06:13
     * @editor: zyy
     */
    public function takeMaterialAdd(){
        if(I('post.dosubmit')){
            if(I('post.id')){
                $effectId = M('MaterialTake')->where(array('id'=>I('post.id')))
                    ->setField(array(
                        'take_place' => I('post.take_place'),
                        'take_date' => I('post.take_date'),
                        'take_users' => I('post.take_users'),
                        'send_user' => I('post.send_user'),
                        'operator' => getLoginUname(),
                        'remark' => I('post.remark'),
                        'update_at' => time()
                    ));

                if($effectId){
                    $this->showtips('耗材领用更新成功');
                }else{
                    $this->showtips('操作失败');
                }
            }
            $orderid = date("Ymd").rand(10000,99999);
            $data = array(
                'order_id' => $orderid,
                'take_place' => I('post.take_place'),
                'take_date' => I('post.take_date'),
                'take_users' => I('post.take_users'),
                'send_user' => I('post.send_user'),
                'operator' => getLoginUname(),
                'remark' => I('post.remark'),
                'add_at' => time(),
                'update_at' => time()
            );
            $add_id = M('MaterialTake')->add($data);
            if($add_id){
                $this->showtips('耗材领用信息添加成功','/take/takeMaterialAdd/id/'.$add_id.'/orderid/'.$orderid.'?res=2-2');
            }else{
                $this->showtips('操作失败');
            }
        }
        if(I('get.id')){
            //组会领用信息
            $takeData = M('MaterialTake')->where(['id'=>I('get.id')])->find();
            //组会的耗材列表
            $drugList = M('Usedetail')->where(['take_orderid'=>I('get.orderid'),'take_type'=>'耗材','delete_at'=>0])->select();
            if($drugList){
                foreach ($drugList as $k=>$val){
                    $drugList[$k]['drugMsg'] = M('Druglist')->where(['id'=>$val['drug_id']])->find();
                }
            }

            $this->assign('drugList',$drugList);
            $this->assign('takeData',$takeData);
        }


        $this->display('take/take_material_add');
    }

    /*
     * 添加领用组会信息详情
     * @date: 2017-11-29下午5:06:13
     * @editor: zyy
     */
    public function takegroup_add_detail(){
        if(I('get.id')){
            //组会领用信息
            $takeData = M('Drugtake')->where(array('id'=>I('get.id')))->find();
            //组会的药品列表
            $drugList = M('Usedetail')->where(['take_orderid'=>I('get.orderid'),'take_type'=>'药品','delete_at'=>0])->select();
            if($drugList){
                foreach ($drugList as $k=>$val){
                    $drugList[$k]['drugMsg'] = M('Druglist')->where(['id'=>$val['drug_id']])->find();
                }
            }
            //组会的转出药品列表
            $outList = M('OutinDetail')->where(['take_orderid'=>I('get.orderid'),'delete_at'=>0])->select();
            if($outList){
                foreach ($outList as $k=>$val){
                    $useDetail = M('Usedetail')->where(['id'=>$val['takedrug_id']])->find();
                    $outList[$k]['outDrugMsg'] = M('Druglist')->where(['id'=>$useDetail['drug_id']])->find();
                    $outList[$k]['takeMsg'] = M('Drugtake')->where(['order_id'=>$val['income_orderid']])->find();
                }
            }

            //组会的转入药品列表
            $inList = M('OutinDetail')->where(['income_orderid'=>I('get.orderid'),'delete_at'=>0])->select();
            if($inList){
                foreach ($inList as $k=>$val){
                    $useDetail = M('Usedetail')->where(['id'=>$val['takedrug_id']])->find();
                    $inList[$k]['inDrugMsg'] = M('Druglist')->where(['id'=>$useDetail['drug_id']])->find();
                    $inList[$k]['takeMsg'] = M('Drugtake')->where(['order_id'=>$val['take_orderid']])->find();
                }
            }

            //组会的还货入库明细
            $return_storage = M('ReturnStock')->where(['take_orderid'=>I('get.orderid')])->select();
            if($return_storage){
                foreach ($return_storage as $k=>$val){
                    $return_storage[$k]['return_drugMsg'] = M('Druglist')->where(['id'=>$val['drug_id']])->find();
                }
            }
            $this->assign('drugList',$drugList);
            $this->assign('outList',$outList);
            $this->assign('inList',$inList);
            $this->assign('return_storage',$return_storage);
            $this->assign('takeData',$takeData);
            $this->display('take/takegroup_add_detail');
        }else{
            $this->showtips('参数缺失');
        }

    }

    /*
     * 还货入库
     * @date: 2017-12-06下午5:06:13
     * @editor: zyy
     */
    public function return_storage(){
        if(I('post.dosubmit') && I('post.usedetail_id')){
            if(I('post.return_num') && I('post.return_storage')){
                if(I('post.return_num') > I('post.last_num')){
                    $this->showtips('还货数量不能大于药品剩余数量');
                }
                $ReturnStock = M('ReturnStock');
                $ReturnStock->startTrans();
                $insert = $ReturnStock->lock(true)->add([
                    'usedetail_id'   => I('post.usedetail_id'),
                    'drug_id'        => I('post.drug_id'),
                    'take_orderid'   => I('post.take_orderid'),
                    'return_num'     => I('post.return_num'),
                    'return_storage' => I('post.return_storage'),
                    'warehouse'      => I('post.warehouse'),
                    'return_user'    => I('post.return_user'),
                    'return_date'    => I('post.return_date')?:date('Y-m-d',time()),
                    'remark'         => I('post.remark'),
                    'add_at'         => time(),
                    'update_at'      => time(),
                ]);

                if($insert){
                    $Stock = M('Stock');
                    $Usedetail = M('Usedetail');
                    $Stock->startTrans();
                    $Usedetail->startTrans();
                    //对应仓库药品库存+还入数量
                    $rs = $Stock->lock(true)->where(['drug_id'=>I('post.drug_id'),'warehouse'=>I('post.return_storage')])->setInc('stock_num',I('post.return_num'));
                    //对应药品剩余量-还入数量
                    $rs2 = $Usedetail->lock(true)->where(['id'=>I('post.usedetail_id')])->setDec('last_num',I('post.return_num'));
                    if($rs && $rs2){
                        $ReturnStock->commit();
                        $Stock->commit();
                        $Usedetail->commit();
                        $this->showtips('还货入库成功');
                    }else{
                        $Stock->rollback();
                        $Usedetail->rollback();
                        $this->showtips('还货入库失败');
                    }
                }else{
                    $ReturnStock->rollback();
                    $this->showtips('还货入库失败');
                }
            }else{
                $this->showtips('还入数量和仓库不能为空');
            }
        }
        //获取要还的药品信息
        $detail = M('Usedetail')->where(['id'=>I('get.id')])->find();
        //获取仓库列表
        $storage = M('Warehouse')->getField('warehouse_id,warehouse_name');
        $this->assign('detail',$detail);
        $this->assign('storage',$storage);
        $this->display('take/return_storage');
    }
}